package javaStudy;

import java.util.Arrays;

public class Main{
    public static void main(String[] args) {
        int test[] = {1, 2, 3, 4, 56, 6, 12, 1, 4, 45, 5};
        Arrays.sort(test);
        System.out.println(Arrays.toString(test));
        int key = 3;
        int result = binarySearch(test,key);

        System.out.println(result);
    }

    public static int binarySearch(int[] test,int key) {
        int length = test.length;
        return binarySearch0(test, 0, length, key);
    }

    public static int binarySearch0(int[] test, int fromIndex, int toIndex, int key) {
        int low = fromIndex;
        int high = toIndex;
        while (low < high) {
            int mid = (low + high) >>> 1;
            int midValue = test[mid];
            if(midValue > key)   //说明在左边
                high = mid - 1;
            else if(midValue <key)
                low = mid + 1;
            else
                return mid;
        }
        return -(low + 1);
    }

}
